/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fsktms.dispatcher;

import fsktms.IMessage;
import fsktms.messagemanager.IMessageListener;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author salm
 */
public class Dispatcher implements Runnable
{
    private DispatchSource dpSource;
    private Map<Integer, IMessageListener> msgListeners = new HashMap<>();
    private long delay = 60;
    
    public Dispatcher(DispatchSource dpS)
    {
        this.dpSource = dpS;
    }
    
    public Dispatcher(DispatchSource dpS, long delay)
    {
        this.dpSource = dpS;
        this.delay = delay;
    }
    
    public Map<Integer, IMessageListener> getMessageListeners()
    {
        return this.msgListeners;
    }
    
    @Override
    public void run()
    {
        while (!dpSource.isClosed())
        {
            try
            {
                while (dpSource.isHasCompletedMessage())
                {
                    IMessage msg = dpSource.getCompletedMessage();
                    IMessageListener listener = this.msgListeners.get(msg.getMagicKey());
                    if (listener != null)
                    {
                        listener.onHasNewMessage(msg);
                    }
                }
                
                Thread.sleep(getDelay());
            }
            catch (Exception ex)
            {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @return the delay
     */
    public long getDelay() {
        return delay;
    }

    /**
     * @param delay the delay to set
     */
    public void setDelay(long delay) {
        this.delay = delay;
    }
    
}
